from audioop import reverse

from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from home.models import ArticleCategory, Article, Comment

from home.models import ArticleCategory, Article
from django.http import HttpResponseNotFound, HttpResponseBadRequest
from django.core.paginator import Paginator, EmptyPage


class IndexView(View):
    """首页广告"""

    def get(self, request):
        """提供首页广告界面"""
        # ?cat_id=xxx&page_num=xxx&page_size=xxx
        cat_id = request.GET.get('cat_id', 1)
        page_num = request.GET.get('page_num', 1)
        page_size = request.GET.get('page_size', 10)
        # 判断分类id
        try:
            category = ArticleCategory.objects.get(id=cat_id)
        except ArticleCategory.DoesNotExist:
            return HttpResponseNotFound('没有此分类')

        # 获取博客分类信息
        categories = ArticleCategory.objects.all()

        # 分页数据
        articles = Article.objects.filter(
            category=category
        )

        # 创建分页器：每页N条记录
        paginator = Paginator(articles, page_size)
        # 获取每页商品数据
        try:
            page_articles = paginator.page(page_num)
        except EmptyPage:
            # 如果没有分页数据，默认给用户404
            return HttpResponseNotFound('empty page')
        # 获取列表页总页数
        total_page = paginator.num_pages

        context = {
            'categories': categories,
            'category': category,
            'articles': page_articles,
            'page_size': page_size,
            'total_page': total_page,
            'page_num': page_num,
        }

        return render(request, 'index.html', context=context)


class DetailView(View):
    def get(self, request):
        comments = Comment.objects.all()
        id = request.GET.get('id')
        try:
            article = Article.objects.get(id=id)
        except Article.DoesNotExist:
            return render(request, '404.html')
        article.total_views += 1
        article.save()
        hot_tags = Article.objects.values("tags").order_by("total_views").distinct()[:9]
        news = Article.objects.order_by("create_time")[:2]
        li = Article.objects.filter(author=article.author)[:3]
        context = {
            'article': article,
            'hot_tags': hot_tags,
            'news': news,
            'comments': comments,
            'list': li,
        }
        return render(request, 'details.html', context=context)

    def post(self, request):
        # 1.获取已经登录用户信息
        user = request.user
        # 2.判断用户是否登录
        if user and user.is_authenticated:
            # 3.登录用户才可以接收form数据
            # 3-1接收评论数据
            id = request.POST.get('id')
            content = request.POST.get('content')
            # 3-2验证文章是否存在
            try:
                art = Article.objects.get(id=id)
            except Article.DoesNotExist:
                return HttpResponseBadRequest("该文章不存在")
            # 3-3保存评论数据
            from home.models import Comment
            Comment.objects.create(
                content=content, article=art, user=user
            )
            # 3-4修改文章的评论数量
            art.comments_count += 1
            art.save()
            # 刷新当前页面
            req_url = request.path + '?id=' + id
            return redirect(req_url)
        else:
            # 4.未登录用户跳转到登录页面
            return redirect('/login')
